package com.ctsi.security.event.role;

import com.ctsi.commons.event.AbstractObserver;
import com.ctsi.commons.event.BaseEvent;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.framework.common.startrun.ComponentFactory;
import com.ctsi.security.PermissionRole;
import com.ctsi.security.domain.RolePermission;
import com.ctsi.security.domain.SRole;
import com.ctsi.security.service.RoleSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;


/**
 * @author Administrator
 *
 */
public class AddRolePermission extends AbstractObserver {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4197411386855893999L;
	private static final Logger logger = LoggerFactory.getLogger(AddRolePermission.class);
    private PermissionRole sroleService;
    private RoleSecurityService roleSecurityService=(RoleSecurityService) ComponentFactory.getBean("roleSecurityService");
//    private ISecurity isecurity=(ISecurity) ComponentFactory.getBean("iSecurity");
	@Override
	public void onEvent(Object[] args) {
		BaseEvent event=(BaseEvent) args[0];
		Map<?,?> context=event.getContext();
		RolePermission rp=context.get("rolePermissionId")==null?null:(RolePermission)context.get("rolePermissionId");
		String action=context.get("action")==null?null:(String)context.get("action");
		if(rp!=null&&"add".equals(action)) {
			logger.info("the {} add permission,result to add permission to son roles!",rp.getRoleId());
			List<SRole> sons=sroleService.getSonRoles(rp.getRoleId());
			rp.setParentRoleId(rp.getRoleId());
			if(UtilValidate.isNotEmpty(sons)) {
			   for(SRole srole : sons) {
				   //是否已经有功能
				   List<RolePermission> temp=roleSecurityService.findRolePermission(new String[] {"roleId","permissionId"}, new String[] {srole.getRoleId(),rp.getPermissionId()});
				   if(UtilValidate.isNotEmpty(temp)) {
					   continue;
				   }
				   rp.setRoleId(srole.getRoleId());
				   rp.setId(UUIDGenerator.getId());
				   roleSecurityService.saveRolePermission(rp);
			   }
			}
		}
	}

	public void setSroleService(PermissionRole sroleService) {
		this.sroleService = sroleService;
	}
	

}
